<template>
  <a-modal
    :title="model && model.id ? '编辑供应商' : '新建供应商'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    okText=""
    @ok="
      () => {
        $emit('ok')
      }
    "
    @cancel="
      () => {
        $emit('cancel')
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item label="id" v-show="false">
          <a-input v-decorator="['id']" />
        </a-form-item>
        <a-form-item label="供应商名">
          <a-input v-decorator="['name', { initialValue: model?.name, rules: [{ required: true }] }]" placeholder="请输入供应商名"/>
        </a-form-item>
        <a-form-item label="初始余额">
          <a-input addonAfter="元" v-decorator="['startAmount', { initialValue: 0 }]" placeholder="请输入初始余额"/>
          付款为正，收款为负
        </a-form-item>
        <a-form-item label="状态" v-show="model && model.id > 0">
          <a-select v-decorator="['status', { initialValue: model?.status }]" placeholder="请选择">
            <a-select-option value="1">合作中</a-select-option>
            <a-select-option value="2">停止合作</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
// 表单字段
const fields = ['startAmount','status','name', 'id']
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    model: {
      type: Object,
      default: () => null,
    },
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 },
      },
    }
    return {
      form: this.$form.createForm(this),
      enabled: false,
    }
  },
  created() {
    console.log('custom modal created')
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
}
</script>
